"""辅助函数"""

import re
from typing import List, Dict, Any
from datetime import datetime


def extract_cairo_code(text: str) -> List[Dict[str, str]]:
    """从文本中提取Cairo代码块"""
    code_blocks = []
    
    # 匹配代码块
    pattern = r'```(?:cairo)?\n?(.*?)```'
    matches = re.findall(pattern, text, re.DOTALL)
    
    for i, code in enumerate(matches):
        code_blocks.append({
            "index": i,
            "language": "cairo",
            "code": code.strip(),
            "lines": len(code.split('\n'))
        })
    
    return code_blocks


def detect_cairo_keywords(text: str) -> List[str]:
    """检测Cairo关键字"""
    keywords = [
        "fn ", "struct ", "trait ", "impl ", "mod ", "contract ",
        "enum ", "let ", "mut ", "const ", "use ", "pub ",
        "if ", "else ", "loop ", "while ", "for ", "match ",
        "return ", "assert ", "panic ", "unreachable "
    ]
    
    found_keywords = []
    for keyword in keywords:
        if keyword in text:
            found_keywords.append(keyword.strip())
    
    return found_keywords


def format_timestamp(timestamp: float) -> str:
    """格式化时间戳"""
    return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")


def sanitize_input(text: str) -> str:
    """清理用户输入"""
    # 移除潜在的恶意字符
    text = re.sub(r'[<>"\']', '', text)
    # 限制长度
    return text[:1000] if len(text) > 1000 else text


def validate_cairo_syntax(code: str) -> Dict[str, Any]:
    """验证Cairo语法（基础检查）"""
    errors = []
    warnings = []
    
    # 检查括号匹配
    if code.count('(') != code.count(')'):
        errors.append("括号不匹配")
    
    if code.count('{') != code.count('}'):
        errors.append("花括号不匹配")
    
    # 检查函数定义
    if "fn " in code and not re.search(r'fn\s+\w+\s*\(', code):
        warnings.append("函数定义格式可能不正确")
    
    # 检查结构体定义
    if "struct " in code and not re.search(r'struct\s+\w+\s*\{', code):
        warnings.append("结构体定义格式可能不正确")
    
    return {
        "valid": len(errors) == 0,
        "errors": errors,
        "warnings": warnings
    }


def extract_error_messages(text: str) -> List[str]:
    """提取错误信息"""
    error_patterns = [
        r'error:\s*(.+)',
        r'panic:\s*(.+)',
        r'CompilationError:\s*(.+)',
        r'RuntimeError:\s*(.+)',
        r'Error:\s*(.+)'
    ]
    
    errors = []
    for pattern in error_patterns:
        matches = re.findall(pattern, text, re.IGNORECASE)
        errors.extend(matches)
    
    return errors
